package com.bilibili.juc.tl;


import java.util.Random;
import java.util.concurrent.TimeUnit;

class MyHouse2{
    int salecount = 0;

    //ThreadLocal<Integer> saleVolume = null;
//    ThreadLocal<Integer> saleVolume = new ThreadLocal<Integer>(){
//        @Override
//        protected Integer initialValue() {
//            //return super.initialValue();
//            return 0;
//        }
//    };


    ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(()->0);

    public void saleVolumeByThreadLocal(){
        saleVolume.set(saleVolume.get()+1);
    }


    public synchronized void saleHouse()
    {
        ++salecount;
    }
}
public class ThreadLocalDemo02 {

    public static void main(String[] args) {
        MyHouse2 house = new MyHouse2();

        for(int i =1;i<=5;i++) {
            new Thread(
                    ()->{
                        int size = new Random().nextInt(5)+1 ;
                        try{
                            //System.out.println(size);
                            for(int j = 1;j<=size; j++){
                                //house.saleHouse();
                                house.saleVolumeByThreadLocal();
                            }
                            System.out.println(Thread.currentThread().getName()+"\t"+"号销售卖出:"+house.saleVolume.get());
                        }
                        finally {
                            house.saleVolume.remove();
                        }
                    }
           ,String.valueOf(i)).start();
        }

        try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println(Thread.currentThread().getName()+"\t"+"共计卖出多少套"+house.saleVolume.get());
    }
}
